let socket = null;


async function downsampleBuffer(buffer, inputSampleRate, outputSampleRate) {
  if (outputSampleRate === inputSampleRate) {
      return buffer;
  }
  const sampleRateRatio = inputSampleRate / outputSampleRate;
  const newLength = Math.round(buffer.length / sampleRateRatio);
  const result = new Float32Array(newLength);
  let offsetResult = 0;
  let offsetBuffer = 0;
  while (offsetResult < result.length) {
      const nextOffsetBuffer = Math.round((offsetResult + 1) * sampleRateRatio);
      let accum = 0, count = 0;
      for (let i = offsetBuffer; i < nextOffsetBuffer && i < buffer.length; i++) {
          accum += buffer[i];
          count++;
      }
      result[offsetResult] = accum / count;
      offsetResult++;
      offsetBuffer = nextOffsetBuffer;
  }
  return result;
}

function floatTo16BitPCM(input) {
  const buffer = new ArrayBuffer(input.length * 2);
  const view = new DataView(buffer);
  for (let i = 0; i < input.length; i++) {
      const s = Math.max(-1, Math.min(1, input[i]));
      view.setInt16(i * 2, s < 0 ? s * 0x8000 : s * 0x7FFF, true);
  }
  return buffer;
}


function hexToFloat32Array(hexString) {
  var bytes = new Uint8Array(hexString.length / 2);
  for (var i = 0; i < bytes.length; i++) {
      bytes[i] = parseInt(hexString.substr(i * 2, 2), 16);
  }
  
  // 假设数据是16位有符号整数
  var int16Array = new Int16Array(bytes.buffer);

  // 将16位整数数组转换为浮点数数组，适合Web Audio API
  var float32Array = new Float32Array(int16Array.length);
  for (var i = 0; i < int16Array.length; i++) {
      // 将16位整数映射到[-1.0, 1.0]的范围，这是Web Audio API需要的格式
      float32Array[i] = int16Array[i] / 32768.0;
  }

  return float32Array;
}


// 二进制流转换为base64 格式。
function getBase64(data) {
  return new Promise((resolve, reject) => {
    const blob = new Blob([data], { type: "audio/wav" }); // 必须指定type类型
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}



function hexToBase64(hexString) {
  // 移除所有非十六进制字符，比如空格、冒号等
  hexString = hexString.replace(/[^a-fA-F0-9]/g, '');

  // 字符串长度必须为偶数
  if (hexString.length % 2 !== 0) {
      throw new Error("十六进制字符串的长度必须为偶数");
  }

  // 创建一个数组，每个元素是一个字节
  const byteArray = new Uint8Array(hexString.length / 2);

  // 循环处理每对十六进制字符，转换为一个字节
  for (let i = 0; i < byteArray.length; i++) {
      byteArray[i] = parseInt(hexString.substr(i * 2, 2), 16);
  }

  // 将字节数组转换为Base64
  const base64String = btoa(String.fromCharCode.apply(null, byteArray));

  return base64String;
}


function test()
{
  console.log("Testing")
}




function createChatWsSocket(url,callBack)
{
  socket = new WebSocket(url);
  socket.onopen = function()
  {
    // console.log("opend ws")
  }
  socket.onmessage = event => {
    callBack && callBack(event)
  }

  socket.onclose = () => {
    // console.log("close ws")
  };
}



function closeChatWs()
{
  if(socket)
  {
    socket.close();
  }
}



function stringToBinary(text) {
  const encoder = new TextEncoder();
  const uint8Array = encoder.encode(text);
  return uint8Array;
}





function splitChat(msg,strMin)
{
  if ((msg == "，" || msg == "。") && msg.length > strMin)
  {
    audioUrl = str(strId)+"-test.wav"
    tempObj = {
        "id":strId,
        "msg" : tempStr,
        "audioUrl": audioUrl
    }
    return 
  }
}





export { downsampleBuffer, floatTo16BitPCM , test , createChatWsSocket , closeChatWs , getBase64 , hexToBase64 , stringToBinary}